package com.hckj.jianzhijia;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.text.InputType;
import android.view.View;
import android.widget.Button;

import com.rey.material.app.Dialog;
import com.rey.material.app.DialogFragment;
import com.rey.material.app.SimpleDialog;
import com.rey.material.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.os.CountDownTimer;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVMobilePhoneVerifyCallback;
import com.avos.avoscloud.AVOSCloud;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.RequestMobileCodeCallback;
import com.hckj.jianzhijia.controllers.RegisterController;
import com.hckj.jianzhijia.listeners.OnBackClickListener;
import com.hckj.jianzhijia.utils.Data;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.ToastUtils;

import java.util.HashMap;
import java.util.List;
import java.util.logging.Handler;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class RegisterActivity extends BaseActivity {

    @InjectView(R.id.imgv_go_back)
    ImageView imgvGoBack;
    @InjectView(R.id.rl_toolbar)
    RelativeLayout rlToolbar;
    @InjectView(R.id.edt_phone_num)
    EditText edtPhoneNum;
    @InjectView(R.id.btn_get_code)
    Button btnGetCode;
    @InjectView(R.id.edt_code)
    EditText edtCode;
    @InjectView(R.id.edt_password)
    EditText edtPassword;
    @InjectView(R.id.imgv_show_password)
    ImageView imgvShowPassword;
    @InjectView(R.id.cb_read_protocol)
    CheckBox cbReadProtocol;
    @InjectView(R.id.tv_read_protocol)
    TextView tvReadProtocol;
    @InjectView(R.id.btn_register)
    Button btnRegister;

    private String phoneNum;
    private String password;
    private String messageCode;
    private boolean hasReadProtocol;
    private RegisterController registerController;
    private boolean passwordSeen = false;

    public final static int COUNT_TIME = -1;
    private boolean ifCountDownTimerOn = false;

    private android.os.Handler countTimeHandler = new android.os.Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == COUNT_TIME) {
                CountDownTimer countDownTimer = new CountDownTimer(60000, 1000) {
                    public void onTick(long millisUntilFinished) {
                        ifCountDownTimerOn = true;
                        btnGetCode.setText("倒计时" + millisUntilFinished/1000);
                    }
                    public void onFinish() {
                        ifCountDownTimerOn = false;
                        btnGetCode.setText("重新获取" );
                    }
                };
                countDownTimer.start();
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        ButterKnife.inject(this);
        registerController = new RegisterController(this);
        initEvent();
    }

    private void initEvent() {
        imgvGoBack.setOnClickListener(new OnBackClickListener(this));
        imgvShowPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (passwordSeen) {//密码可见
                    edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    imgvShowPassword.setImageResource(R.drawable.looked);
                    passwordSeen = false;
                } else {
                    edtPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    imgvShowPassword.setImageResource(R.drawable.look);
                    passwordSeen = true;
                }
            }
        });
        tvReadProtocol.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), WebPageActivity.class);
                intent.putExtra("WebPageType",WebPageActivity.WEBPAGE_REGISTER);
                startActivity(intent);
            }
        });

        btnRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                getDataFromEdt();
                if (!registerController.checkAllData(phoneNum, password, messageCode, hasReadProtocol)) {
                    return;
                }


                AVOSCloud.verifyCodeInBackground(messageCode, phoneNum, new AVMobilePhoneVerifyCallback() {
                    @Override
                    public void done(AVException e) {
                        if (e == null) {
                            ToastUtils.showToast(getApplicationContext(), "验证码验证成功");
                            Intent intent = new Intent(getApplicationContext(), RegisterInfoActivity.class);
                            intent.putExtra("phoneNum", phoneNum);
                            intent.putExtra("password", password);
                            startActivity(intent);
                            finish();
                        } else {
                            ToastUtils.showToast(getApplicationContext(), ExceptionUtils.getExceptionInfo(e));
                        }
                    }
                });


            }
        });

        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(ifCountDownTimerOn){
                    return;
                }
                getDataFromEdt();
                if (!registerController.checkPhoneNum(phoneNum)) {
                    return;
                } else {
                    MessageCodeNetWork messageCodeNetWork = new MessageCodeNetWork(phoneNum);
                    messageCodeNetWork.execute();
                }
            }
        });
    }

    public void getDataFromEdt() {
        phoneNum = edtPhoneNum.getText().toString().trim();
        password = edtPassword.getText().toString().trim();
        messageCode = edtCode.getText().toString().trim();
        hasReadProtocol = cbReadProtocol.isChecked();
    }

    class MessageCodeNetWork extends AsyncTask<Void, Void, String> {

        private String phoneNum;
        public MessageCodeNetWork(String phoneNum) {
            this.phoneNum = phoneNum;
        }

        @Override
        protected void onPreExecute() {

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... params) {

            AVQuery<AVUser> avUserAVQuery = AVUser.getQuery();
            avUserAVQuery.whereEqualTo("username", phoneNum);

            try {
                List list = avUserAVQuery.find();
                if (list.size() != 0) {
                    return "当前手机号已经注册";
                }
            } catch (AVException e) {
                return ExceptionUtils.getExceptionInfo(e);
            }
            countTimeHandler.sendEmptyMessage(COUNT_TIME);

            HashMap<String, Object> env = new HashMap<String, Object>();
            env.put("name", Data.appName);
            try {
                AVOSCloud.requestSMSCode(phoneNum, Data.messageTemplate, env);
            } catch (AVException e) {
                return ExceptionUtils.getExceptionInfo(e);
            }
            return null;
        }

        @Override
        protected void onPostExecute(String a) {
            if (a != null) {
                ToastUtils.showToast(getApplicationContext(), a);
            }
            super.onPostExecute(a);
        }
    }




}
